<?php
namespace Infinity;


class User extends \Infinity\AbstractEntity {
  
    public function __construct($id=null) {
        if(!$id)
            $id = $GLOBALS['user']->uid;
        parent::__construct($id);
    }

    protected function init() {
        $this->setEntityType('user');
    }

    public static function create() {
        return new self(array(
            'name' => '',
            'mail' => '',
            'pass' => '',
            'status' => 0
        ));
    }

    public static function load($id) {
        $self = new self($id);
        if($self->isEmpty()) return false;
        return $self;
    }

    public function save() {
        $edit = array();
        if(!empty($this->entity->pass)) {
            $edit = array(
                'pass' => $this->entity->pass
            );
        }
        user_save($this->entity, $edit);
        return $this;
    }

    /**
    * @param null $name
    */
    public static function switchUser($uid) {
        global $user;

        if ($user->uid) {
            module_invoke_all('user_logout', $user);
        }
        if ($account = user_load($uid)) {
            $old_uid = $user->uid;
            $user = $account;
            $user->timestamp = time() - 9999;
            if (!$old_uid) {
            // Switch from anonymous to authorized.
            drupal_session_regenerate();
            }
            $edit = array();
            user_module_invoke('login', $edit, $user);
        }
        elseif ($user->uid) {
            session_destroy();
        }
    }

    public static function toRoleId($role) {
        if(is_numeric($role)) {
            return $role;
        } else {
            $role = user_role_load_by_name($role);
            return $role->rid;
        }
    }

    public static function getUsersByRole($role) {
        $rid = self::toRoleId($role);
        $uids = db_query('SELECT DISTINCT(ur.uid) FROM {users_roles} AS ur WHERE ur.rid = (:rid)', array(
            ':rid' => $rid
        ))->fetchCol();
        return user_load_multiple($uids);
    }

    public function addRole($role) {
        user_multiple_role_edit(array($this->id()), 'add_role', self::toRoleId($role));
        return $this;
    }

    public function removeRole($role) {
        user_multiple_role_edit(array($this->id()), 'remove_role', self::toRoleId($role));
        return $this;
    }

    public function isRole($role) {
        return in_array(self::toRoleId($role), array_keys($this->entity->roles));
    }
}